package com.xyxy.platform.website.common.web.filter;

import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.core.web.extensions.ajax.AjaxUtils;
import com.xyxy.platform.website.common.constants.AppConstants;
import com.xyxy.platform.website.common.vo.CurrentLoginUser;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * 登录 session 过滤
 *
 * @author: VirtueCai
 */
public class SessionFilter extends BaseFilter {

    private static String loginUrl = "/login";

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获得 Session
        HttpSession session = request.getSession();
        // 获得用户请求的URI
        String path = request.getRequestURI();
        // 从 Session 获取登录用户信息
        CurrentLoginUser loginUser = (CurrentLoginUser) session.getAttribute(AppConstants.CURRENT_USER);

        // 判断如果没有取到员工信息,就跳转到登陆页面
        if (null == loginUser) {
            // 是否记住, 含有 cookie, 自动登录

            //是否是 ajax 请求
            if (AjaxUtils.isAjaxRequest(request)) {
                // 向http头添加 状态 sessionstatus
                response.setHeader("sessionstatus", "timeout");
                response.setStatus(403);
                //向http头添加登录的url
                response.addHeader("loginPath", loginUrl);
                request.getSession().setAttribute(AppConstants.LOGIN_SUCCESS_REDIRECT_URL, request.getHeader(AppConstants.LOGIN_SUCCESS_REDIRECT_URL));
            } else {
                // 判断get请求, 记录被拦截url, 登录后继续跳转
                if (request.getMethod().equalsIgnoreCase("GET")) {
                    // 重定向 url
                    String redirectUrl = generateRedirectUrl(request);
                    if (StringUtils.isNotEmpty(redirectUrl)) {
                        request.getSession().setAttribute(AppConstants.LOGIN_SUCCESS_REDIRECT_URL, redirectUrl);
                    }
                }
                // 跳转到登陆页面
                response.sendRedirect(request.getContextPath() + loginUrl);
                return;
            }
            chain.doFilter(request, response);
        } else {
            // 已经登陆,继续此次请求
            chain.doFilter(request, response);
        }

    }

    /**
     * 构造get 请求重定向url
     * @param request
     * @return
     */
    private String generateRedirectUrl(HttpServletRequest request) {
        StringBuffer urlBuffer = new StringBuffer("");
        //基本url
        urlBuffer.append(request.getRequestURI().replace(request.getContextPath(), ""));
        //参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> paramsKeySet = parameterMap.keySet();
        if (Collections3.isEmpty(paramsKeySet)) {
            return null;
        }
        for (String paramKey : paramsKeySet) {
            String value = request.getParameter(paramKey);
            if (StringUtils.isEmpty(value)) continue;
            urlBuffer.append(urlBuffer.indexOf("?") == -1 ? "?" : "&");
            urlBuffer.append(paramKey).append("=").append(value);
        }
        return urlBuffer.toString();
    }


}
